﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using FacebookXmpp;
using XFControls.XFPanels;
using XDAFacebook;
using XFControls.Utils;
using XFControls.XFPanels.XFPanelItems;
using XFItemControls.XFPanels.XFPanelItems;
using XFSenseUI;
using XFSenseUI.XFItems;
using XFSenseUI.XFItems.SenseControls;
using System.Threading;

namespace XFItemControls.XFPanels
{
    public partial class XFChatConversation : SenseListPanel
    {
        private Person _person;
        private XFChatConversationHistory _hist;
        private Thread _refreshThread;


        public XFChatConversation(Person person)
        {
            _person = person;
            InitializeComponent();

            _refreshThread = new Thread(new ThreadStart(RefreshConversation));
            _refreshThread.Start();

            Add(new XFItemBackHeader());

            _hist = new XFChatConversationHistory(person);
            AddSenseItem(_hist);


            var tb = new SenseItemTextBox() { SendButton = true };
            
            tb.SetHeight(100);
            tb.Click += (o, e) =>
                {
                    _person.SendMessage(tb.Text);
                    _hist.AddRange(_person.MessagesWhere(r => r.To.Id == _person.Id || r.From.Id == _person.Id));
                    tb.Text = "";
                };

            AddSenseItem(tb);
            
            /*
            var buttons = new XFItemTwoButtons();

            SenseControlButton rb = buttons.RightButton;
            SenseControlButton lb = buttons.LeftButton;

            rb.ButtonText = Settings.LocalizationStrings.Submit;
            lb.ButtonText = Settings.LocalizationStrings.Cancel;

            lb.Clicked += (o, e) => EnableSlide();

            rb.Clicked += (o, e) =>
            {
                _person.SendMessage(tb.Text);
                _hist.AddRange( _person.MessagesWhere(r => r.To.Id == _person.Id || r.From.Id == _person.Id) );
            };
            
            rb.Style.Padding = 20;
            lb.Style.Padding = 20;

            Add(buttons);
             */ 
        }

        public void RefreshConversation()
        {
            while(true)
            {
                var newResponses = _person.MessagesWhere(r => r.To.Id == _person.Id || r.From.Id == _person.Id);
                if (newResponses.Count > 0)
                {
                    _hist.AddRange(newResponses);
                    _hist.Invalidate(true);
                }
                Thread.Sleep(500);
            }   

        }

        public XFChatConversation(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }
    }
}
